package struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.form.ActionForm;
import struts.form.FullForm;
import struts.form.XmlBean;

/**
 * Servlet implementation class ActionServlet
 */
@WebServlet("/ActionServlet")
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String path = getPath(request.getServletPath());
		Map<String, XmlBean> map = (Map<String, XmlBean>)getServletContext().getAttribute("struts");
		XmlBean xmlBean = map.get(path);
		String formClass = xmlBean.getFormClass();
		ActionForm form = FullForm.full(formClass, request);
		String actionType = xmlBean.getActionClass();
		Action action = null;
		String url = "";
		try{
			Class clazz = Class.forName(actionType);
			action = (Action)clazz.newInstance();
			url = action.execute(request,form,xmlBean.getActionForward());
		}catch(Exception e){
			System.out.println("严重：控制器异常");
		}
		
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	
	private String getPath(String servletPath){
		return servletPath.split("\\.")[0];
	}
	
	
}
